#!/usr/bin/env bash

# Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

srcdir=ros_comm-${pkgver}

extra_args=()
if [ -z "${feature_test}" ]; then
    extra_args+=(-DCATKIN_ENABLE_TESTING=OFF)
fi

if [ "${arch}" != "${host_arch}" ]; then
    # NOTE: catkin need correct CMAKE_PREFIX_PATH to generate msgs and srvs
    # if not set, CMAKE_PREFIX_PATH -> CATKIN_WORKSPACES -> CATKIN_MESSAGE_GENERATORS will be wrong
    # So we add EXTRA_CATKIN_WORKSPACES_PATH or EXTRA_CATKIN_WORKSPACES_PATH_FOR_GENMSG to make it work
    extra_args+=(-DEXTRA_CATKIN_WORKSPACES_PATH_FOR_GENMSG=/host/usr)

    # FIXME: better way to find cross Python?
    extra_args+=(-DPYTHON_EXECUTABLE=/host/usr/bin/python3.12)
    extra_args+=(-DPYTHON_LIBRARY=/usr/lib/libpython3.12.so)
    extra_args+=(-DPYTHON_INCLUDE_DIR=/usr/include/python3.12)
else
    extra_args+=(-DCMAKE_PREFIX_PATH=/usr)
fi

for dir in \
    utilities/xmlrpcpp tools/rostest utilities/roswtf utilities/roslz4 tools/rosgraph clients/roscpp \
    utilities/message_filters tools/topic_tools tools/rostopic \
    tools/rosservice tools/rosparam tools/rosout tools/rosnode tools/rosmsg tools/rosmaster \
    tools/roslaunch tools/rosbag_storage tools/rosbag clients/rospy ros_comm
do
    cmake \
        -S ${srcdir}/${dir} \
        -B build/${dir} \
        -DCMAKE_BUILD_TYPE=Release \
        -DCMAKE_INSTALL_PREFIX=/usr \
        -DCMAKE_INSTALL_LIBDIR=/usr/lib \
        ${extra_args[@]} \
        || exit 1
    make -C build/${dir} -j ${MAX_JOBS} || exit 1

    case ${dir} in
        utilities/xmlrpcpp|utilities/roslz4|tools/rostest|clients/roscpp|tools/topic_tools|tools/rosbag_storage):
            make -C build/${dir} install || exit 1
            ;;
    esac
done
